/**
 * @description APP业务工具类
 */

/**
 * @description 获取菜谱ID
 * @param {*} _
 * @returns
 */
export const getRecipeId = _ => {
  // id，（格式：R + 年月日时分秒）
  return `R${g_dayjs().format('YYYYMMDDHHmmss')}`
}

/**
 * @description 获取菜谱的名称
 * @param {*} data
 * @returns
 */
export const getRecipeStepName = data => {
  const { recipeCategoryList } = storeToRefs(useRecipeStore())

  console.log('recipeCategoryList.value', recipeCategoryList.value)
  let name = ''
  const getLabel = value => {
    return (
      recipeCategoryList.value.find(item => item.value === value)?.label || ''
    )
  }
  switch (data.ingredientType) {
    // 食材
    case 'material':
      name =
        data.materialList
          .map(item => item.ingredientName + item.goal + '克')
          .join('，') + `，翻倒${data.turnCount}次`
      break
    // 调料
    case 'flavour':
      name = data.ingredientName + data.goal + '克'
      break
    default:
      name = getLabel(data.ingredientType) + data.ingredientName
      break
  }

  return name
}

/**
 * @description 获取菜谱的targetId
 * @param {*} data
 * @returns
 */
export const getRecipeTargetId = data => {
  return ['heater', 'shovel'].includes(data.ingredientType)
    ? data.target.slice(0, -1)
    : data.target
}

/**
 * @description 获取菜谱的goal
 * @param {*} data
 * @returns
 */
export const getRecipeGoal = data => {
  return ['heater', 'shovel'].includes(data.ingredientType)
    ? data.target.slice(-1) * 1
    : data.goal
}

/**
 * 根据target匹配ingredientType的值
 * @param obj
 * @param target
 */
export const findAllValues = (obj, target) => {
  let values = [[], []]

  for (let key in obj) {
    if (obj[key].value === target + '') {
      values[0].push(obj[key].value)
      values[1].push(obj[key].label)
      return values
    }

    if (obj[key]?.ingredientList?.length) {
      const found = findAllValues(obj[key].ingredientList, target)
      if (found[0].length) {
        values[0] = [obj[key].value, ...found[0]]
        values[1] = [obj[key].label, ...found[1]]
        return values
      }
    }
  }

  return values
}

/**
 * 通过SN号查询绑定的设备信息
 * @param {string} deviceSn SN号
 * @returns {deviceInfo} 设备信息，没有返回undefined
 */
export const getDeviceInfoBySn = deviceSn => {
  return useDeviceStore().bindDeviceList.find(device => device.sn === deviceSn)
}

/**
 * 通过status查询绑定的设备信息
 * @param {string} status 设备状态，默认空闲状态
 * @returns {deviceList} 设备列表，没有返回空数组[]
 */
export const getDeviceInfoByStatus = (
  status = g_i.device.DeviceStatus.Idle
) => {
  return useDeviceStore().bindDeviceList.filter(
    device => device.status * 1 === status
  )
}

/**
 * 通过ID查询菜谱烹饪记录
 * @param {string} cookingId 烹饪ID
 * @returns {cookingInfo} 菜谱烹饪信息，没有返回undefined
 */
export const getCookingInfoById = cookingId => {
  return useCookingStore().cookingItemList.find(
    cooking => cooking.cookingId === cookingId
  )
}

/**
 * 通过ID查询菜谱信息
 * @param {string} recipeId 菜谱ID
 * @returns {recipeInfo} 菜谱信息，没有返回undefined
 */
export const getRecipeInfoById = recipeId => {
  const { recipeLibraryList, recipeFormulatingList } = useRecipeStore()

  return [...recipeLibraryList, ...recipeFormulatingList].find(
    recipe => recipe.id === recipeId
  )
}

/**
 * 计算菜谱烹饪进度
 * @param {object} cookingInfo 烹饪信息
 * @param {object} recipeInfo 菜谱信息
 * @param {object} deviceInfo 设备信息
 * @returns {object} 进度信息
 */
export const calculateProgress = (cookingInfo, recipeInfo, deviceInfo = {}) => {
  const stepList = recipeInfo.stepList
  const sumDurations = steps =>
    steps?.reduce((sum, step) => sum + (step.timeOffset ?? 0) * 1, 0) ?? 0
  const totalSeconds = sumDurations(stepList)
  const curStepIndex = cookingInfo.step - 1
  const curStepSecond = stepList?.[curStepIndex]?.timeOffset || 0

  // 边界条件处理
  if (totalSeconds <= 0) {
    return { remainSeconds: 0, curStepProgress: 0, progress: 0 }
  }
  // 未开始烹饪的情况
  if (!cookingInfo.step) {
    return { remainSeconds: totalSeconds, curStepProgress: 0, progress: 0 }
  }
  // 所有步骤已完成的情况
  if (curStepIndex >= stepList.length) {
    return { remainSeconds: 0, curStepProgress: 100, progress: 100 }
  }

  // 计算之前所有步骤的总时间（秒）
  const beforeStepsSeconds = sumDurations(stepList.slice(0, curStepIndex))
  // 计算当前步骤已进行的时间（秒）
  // 设备暂停中计算时间差
  const stepTimeDiff =
    deviceInfo.status === g_i.device.DeviceStatus.Pause
      ? cookingInfo.stepPauseStartTime -
        cookingInfo.stepStartTime -
        cookingInfo.stepPauseDuration
      : Date.now() - cookingInfo.stepStartTime
  const currentStepElapsed = Math.min(
    Math.max(0, stepTimeDiff / 1000),
    curStepSecond
  )
  // 当前步骤的时间与进度
  const totalElapsed = beforeStepsSeconds + currentStepElapsed
  const progress = Math.min(
    Math.round((totalElapsed / totalSeconds) * 100),
    100
  )
  console.log('之前所有步骤的总时间（秒）', beforeStepsSeconds)
  console.log('当前步骤已进行的时间（秒）', currentStepElapsed)

  return {
    remainSeconds: Math.max(0, totalSeconds - totalElapsed).toFixed(0),
    curStepProgress: (currentStepElapsed / curStepSecond) * 100,
    progress
  }
}
